#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

//#define _GNU_SOURCE         /* For mempcpy */

int main(int argc, char** argv) {
	
	if(argc !=2) {
		fprintf(stderr, "No input file. Usage %s filename\n", argv[0]);
		exit(1);
	}
	

	int fd = open(argv[1], O_RDONLY);
	if(fd == -1) {
		 perror(argv[1]);
		 exit(1);
	}
	
	char crypted_filename[256];
	sprintf(crypted_filename, "%s.cr", argv[1]);	
	int fdw =  open(crypted_filename, O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
	if(fdw == -1) {
		perror(crypted_filename);
		close(fd);
		exit(1);
	}
        

	char *src_buffer;
	char *dst_buffer;
        int buffer_size = 32;
        if( ((src_buffer=(char *)malloc(buffer_size)) == NULL) || ((dst_buffer=(char *)malloc(buffer_size)) == NULL) ) {
                fprintf(stderr, "Can not allocate %d bytes of memory", buffer_size);
		close(fd);
		close(fdw);
                exit(1);
        }

	int bytes_read;
	do {
		bytes_read = read(fd, src_buffer, buffer_size);
		if(bytes_read != buffer_size) {
			printf("The sum of read bytes less than the buffer size: %d \n", bytes_read);
			write(fdw, src_buffer, bytes_read);	
		}
		else {
			memcpy(dst_buffer, src_buffer, buffer_size/2);
			memcpy(dst_buffer+buffer_size/2, src_buffer+buffer_size/2, buffer_size/2);
			write(fdw, dst_buffer, bytes_read);
		}
	} while (bytes_read == buffer_size);

	close(fd);
	close(fdw);
	free(src_buffer);
	free(dst_buffer);	
	return 0;
}
